<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { removeToken, removeRole, removeCode, getCode } from "@/utils/auth";
export default {
  name: "App",
  data() {
    return {
      websock: null,
      notice: null,
      heartBeat: null
    };
  },
  computed: {
    ...mapState({
      hasReadId: state => state.app.hasReadId,
      msg: state => state.app.msg,
      code: state => state.user.code
    })
  },
  watch: {
    code: function(val) {
      if (val) {
        if (this.websock) {
          this.websock.close(); // 关闭websocket
        }
        this.initWebSocket();
      } else {
        this.websock.close();
      }
    },
    hasReadId: function(val) {
      if (val === "all") {
        this.websock.send(JSON.stringify({ type: "all" }));
        this.setReadId(null);
      } else if (val) {
        console.log(val);
        this.websock.send(JSON.stringify({ id: val, type: "single" }));
        this.setReadId(null);
      }
    }
  },
  methods: {
    ...mapMutations("app", ["setMsg", "setReadId"]),
    //初始化weosocket
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持WebSocket");
        return false;
      }
      if (getCode()) {
        const wsuri = "ws://zhuolong.zhixiu.vip/ws?code=" + getCode();
        this.websock = new WebSocket(wsuri);
        this.websock.onopen = this.websocketonopen;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      } else {
        removeToken();
        removeRole();
        removeCode();
      }
    },
    //连接成功
    websocketonopen(e) {
      console.log("WebSocket连接成功", e);
      this.heartBeat = setInterval(() => {
        this.websock.send("beat");
        console.log("beat", new Date());
      }, 1000 * 60 * 9);
    },
    //接收后端返回的数据，可以根据需要进行处理
    websocketonmessage(e) {
      var vm = this;
      let msg = JSON.parse(e.data);
      console.log(msg);
      if (msg.message) {
        this.setMsg(msg.message);
      } else if (msg.info) {
        let hasRead = false;
        this.notice = this.$notify.info({
          title: msg.info.type === "user" ? "用户注册" : "商品订单",
          message: msg.info.message,
          onClose: () => {
            if (!hasRead) {
              let arr = this.msg;
              arr.push(msg.info);
              this.setMsg(arr);
            }
          },
          onClick: () => {
            this.websock.send(
              JSON.stringify({ id: msg.info.id, type: "single" })
            );
            hasRead = true;
            this.notice.close();
            if (msg.info.type === "user") {
              this.$router.push("/user-mng/ordinary-user");
            } else {
              this.$router.push("/order-mng/normal-order");
            }
          }
        });
      }
    },
    //连接建立失败重连
    websocketonerror(e) {
      console.log(`连接失败的信息：`, e);
      this.initWebSocket(); // 连接失败后尝试重新连接
    },
    //关闭连接
    websocketclose(e) {
      console.log("断开连接", e);
      clearInterval(this.heartBeat);
      console.log(new Date());
    }
  },
  created() {
    if (this.websock) {
      this.websock.close(); // 关闭websocket连接
    }
    this.initWebSocket();
  },
  destroyed() {
    //页面销毁时关闭ws连接
    if (this.websock) {
      this.websock.close(); // 关闭websocket
    }
  }
};
</script>
